<?php

class Listing_Form_CommentForm extends Ac_Form 
{
    /**
     *
     * @var Model_User current user logged in
     */
    private $_user;
    private $_upload_activated;
    private $_resume_filename;

    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $formDecorators = array(
        'PrepareElements',
        array('ViewScript', array('viewScript' => 'index/customization/send-message.phtml'))

    );

    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('escape' => false, 'placement' => 'APPEND', 'tag' => 'section', 'class' => 'intro')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
    );

    /**
     *
     * @var Model_Listing listing
     */
    private $_listing;

    public function __construct($options = array())
    {
        $this->_user = !empty($options['user']) ? $options['user'] : null ;
        $this->_listing = !empty($options['listing']) ? $options['listing'] : null;
        $this->_upload_activated = false;
        if (!empty($options['allow_upload'])) {
            $this->_upload_activated = true;
        }

        parent::__construct($options);
    }

    protected function newMessage()
    {
        //$form = $this->getNewSubForm();
        //$form->setDecorators($this->subFormDecorators);

        $element = new Zend_Form_Element_Hidden('sender');
        $element->setValue(($this->_user instanceof Model_User ? $this->_user->_id : ''));
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        $this->addElement($element);

        $element = new Zend_Form_Element_Hidden('listing');
        $element->setValue(($this->_listing instanceof Model_Listing ? $this->_listing->_id : ''));
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        $this->addElement($element);

        /* Email */
        $this->addElement('text', 'email', array(
            'id'      => 'email',
            'name'      => 'email',
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('EmailAddress', true, array('messages' => array(Zend_Validate_EmailAddress::INVALID_FORMAT => 'Valid email required'))),
            ),
            'decorators' => $this->elementDecorators,

            'required'   => true,
            'label'      => 'Email Address',
            'value'      => ($this->_user instanceof Model_User ? $this->_user->email : '')
        ));

        /* Phone */
        $this->addElement('text', 'phone', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('Int', true, array('messages' => 'Numbers only')),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => true,
            'label'      => 'Mobile:',
            'value'      => ($this->_user instanceof Model_User ? $this->_user->phone : '')
        ));

        /* Message */
        $this->addElement('textarea', 'message', array(
            'filters'    => array('StringTrim'),
            'description'=> '<em>3000</em> characters remaining',
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => true,
            'label'      => 'Message',
            'attribs'     => array('class' => 'to_limit')
        ));

        if ($this->_upload_activated) {
            /* Resume */
            $this->addElement('file', 'resume', array(
                'description'=> '.doc, .docx, .pdf, .ods',
                'decorators' => array(
                    'File',
                    'Errors',
                ),
                'required'   => false,
                'label'      => 'Resume',
            ));
        }

        /* Newsletter */
        $this->addElement('checkbox', 'newsletter', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                //'EmailAddress',
            ),
            'value'   => 1,
            'decorators' => $this->elementDecorators,
            'required'   => false,
            //'label'      => 'I would like to receive the AsiaClassified Newsletter',
        ));

        /* Submit Button */
        $this->addElement('button', 'Send_Message', array(
            'description' => 'By clicking Send Message, you agree to AsiaClassified’s <a href="/default/index/term-of-use">Terms of Use</a> and <a href="/default/index/privacy">Privacy Policy</a>.',
            'required'    => false,
            'ignore'      => true,
            'label'       => 'Send Message',
            'type'        => 'submit',
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'button_em')),
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'div', 'class' => 'remark')),

            ),
        ));
    }

    public function init()
    {
        parent::init();
        $view = Zend_Registry::get('Zend_View');
        $view->url();

        //Choose the method to transfer parameters
        $this->setMethod('post');
        $this->setAction($view->url());
        $this->newMessage();
        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['upload_activated'] = $this->_upload_activated;

        $this->getDecorator('ViewScript')->setOptions($opt);
    }

    public function save()
    {

        $content = $_POST['message'];
        $email   = $_POST['email'];
        $phone   = $_POST['phone'];

        //create an account with minimal informations
        //$user_id = $_POST['sender'];
        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
        } elseif ($user = Model_User::one(array('email' => $email))) {

        }
        $new = false;
        if (empty($user)) {
            $new = true;
            $user           = new Model_User();
            $user->email    = $email;
            $user->phone    = $phone;
            $user->username = Model_User::generateUsername($email);
            $password = Model_User::getNewPassword();
            $user->password = Model_USer::generatePassword($password);
            $user->save();

            //$user = Model_User::create($data);
            $user_id = (string)$user->_id;
        }

        if (!empty($user->status) && $user->status != Model_User::STATUS_ACTIVE) {
            return false;
        }

        $listing = $_POST['newmessage']['listing'];
        $listing = Model_Listing::find($listing);

        $subject_sender = Zend_Registry::get('Zend_View')->t('你已成功发了私信给 __1__', null, $listing->user->un);
        $message_sender = $content;
        $email_sender   = $email;
        $email_poster = $listing->user->email;

        //var_dump($_POST, $phone);exit;
        $un = explode('@', $email_sender);
        $subject = Zend_Registry::get('Zend_View')->t('__1__ sent you a message on Asiaclassified', null, $un[0]);
        
        //send the message to the sender
        if ($new) {
            Ac_Util::sendEmail($subject_sender, $message_sender, $email_sender, true, array('listing' => $listing, 'user' => $user, 'password' => $password), Ac_Mail::TEMPLATE_SENDMESSAGE_SENDER, AC_Mail::WEBMASTER, $this->_resume_filename);
        } else {
            Ac_Util::sendEmail($subject_sender, $message_sender, $email_sender, true, array('listing' => $listing, 'username' => $user->username), Ac_Mail::TEMPLATE_SENDMESSAGE_SENDER, AC_Mail::WEBMASTER, $this->_resume_filename);
        }
		
		//check how many pending message to poster by sender
		$pending = Model_Message::all(array('fo.email' => $email_sender, 'st' => Model_Message::STATUS_PENDING))->count();
		//echo $pending;exit();
		if($pending < 10)
		//if(true)
		{
			$spam_message = new Model_Message();
			$spam_message->fo = array('email' => $email_sender, 'name' => 'AsiaClassified');
			$spam_message->to = $email_poster;
			$spam_message->su = "[".$listing->tl_en."]";
			$spam_message->message_txt = $message_sender;
			$spam_message->ls = $listing->_id;
			$spam_message->st = Model_Message::STATUS_PENDING;
			$spam_message->save();
		}else
		{
			//$spams = Model_Message::update(array('fo.email' => $email_sender, 'st' => Model_Message::STATUS_PENDING), array('$set' => array('st' => Model_Message::STATUS_SPAM), false, true));
			$spams = Model_Message::all(array('fo.email' => $email_sender, 'st' => Model_Message::STATUS_PENDING));
			foreach($spams as $spam)
			{
				$spam->st = Model_Message::STATUS_SPAM;
				$spam->save();
			}
			
			$spam_message = new Model_Message();
			$spam_message->fo = array('email' => $email_sender, 'name' => 'AsiaClassified');
			$spam_message->to = $email_poster;
			$spam_message->su = "[".$listing->tl_en."]";
			$spam_message->message_txt = $message_sender;
			$spam_message->ls = $listing->_id;
			$spam_message->st = Model_Message::STATUS_SPAM;
			$spam_message->save();
			
			$subject = Zend_Registry::get('Zend_View')->t('SPAM ALERT');
		    Ac_Util::sendEmail($subject, '', 'help@asiaclassified.com', true, array('email_add' => $email_sender), Ac_Mail::TEMPLATE_SPAM_ALERT); 
		}
		
        //send the message to the poster
        //Ac_Util::sendEmail($subject, $message_sender, $email_poster, true, array('listing' => $listing, 'email_sender' => $email_sender, 'phone_number' => $phone), Ac_Mail::TEMPLATE_SENDMESSAGE_POSTER, array('email' => $email_sender, 'name' => 'AsiaClassified'), $this->_resume_filename);
    }

    public function isValid($post = array())
    {
        $post = $post;
        $test1 = parent::isValid($post);
        $test2  = true;
        $output = '';
        //save file if needed
        if ($this->_upload_activated === true && !empty($_FILES)) {
            //move_uploaded_file($_FILES['upload1']['tmp_name'], '/tmp/test.jpg');
            //var_dump($_FILES, is_uploaded_file($_FILES['upload1']['tmp_name']));exit;
            $res = Ac_Util::uploadMessageFile();
            $finfo = new finfo(FILEINFO_MIME, '/usr/share/misc/magic');
            foreach($res as $file) {
                //test file type
                $mime = $finfo->file($file);
                $mime = explode('; ',$mime);
                if ($mime[0] == 'application/zip') {
                    if (substr($file, -4) != 'docx') {
                        $this->getElement('resume')->addError('The file uploaded is not supported!');
                        $test2 = false;
                    }
                } else if ($mime[0] == 'application/octet-stream' ) {
                    if (substr($file, -3) != 'odt') {
                        $this->getElement('resume')->addError('The file uploaded is not supported!');
                        $test2 = false;
                    }
                } else if (!in_array($mime[0], array('text/plain', 'application/pdf', 'application/msword', 'application/vnd.ms-office'))) {
                    $this->getElement('resume')->addError('The file uploaded is not supported!');
                    $test2 = false;
                }

                if ($test2) {
                    exec('/usr/bin/clamscan "'.$file.'" --stdout --scan-mail=no --scan-ole2=no --scan-pe=no --scan-html=no --no-summary -i', $output);
                    if(!empty($output)) {
                        $this->getElement('resume')->addError('The uploaded file contains a virus!');
                        $test2 = false;
                        unlink($file);
                    }
                }
                if ($test2) {
                    $this->_resume_filename[] = $file;
                }
            }
        }

        //Check Bad Words in Title
        if (Ac_Util::checkBadWord($post['message'])) {
            $this->getSubForm('newmessage')->getElement('message')->addError('Your message contains banned words');
            $test2 = false;
        }

        //Check the two validations
        if ($test1 && $test2){
            return true;
        }
        else {
            return false;
        }
    }

    private function getNewSubForm()
    {
        $form = new Ac_SubForm();
        return $form;
    }
}
